package com.cc.micro.controller;

import com.cc.micro.api.vo.InvestRankView;
import com.cc.micro.common.enumeration.RedisConstant;
import com.cc.micro.common.util.CommonUtil;
import com.cc.micro.common.web.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author CC
 * time 2023-07-02
 * description
 */
@RestController
@Api(tags = "投资理财产品接口")
@RequestMapping("/invest")
public class InvestController extends BaseController{
    @ApiOperation(value = "展示投资排行榜",notes = "投资金额最高的三位")
    @GetMapping("/showRank")
    public Result<List<InvestRankView>> rank(){
        //从缓存中获取降序的三位高分投资人信息
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.
                opsForZSet().reverseRangeWithScores(
                        RedisConstant.INVEST_RANK, 0, 2);
        //缓存命中时
        if (!CollectionUtils.isEmpty(typedTuples)) {
            List<InvestRankView> list=new ArrayList<>();
            typedTuples.forEach(tuple->{
                InvestRankView investRankView = new InvestRankView();
                investRankView.setPhone(tuple.getValue());
                investRankView.setMoney(tuple.getScore());
                list.add(investRankView);
            });
            return Result.ok(list);
        }
        //缓存未命中时
        List<InvestRankView> list=bidInfoService.showRank();
        //数据库也没有
        if (CollectionUtils.isEmpty(list)) {
            return Result.ok(Collections.emptyList());
        }
        //进行缓存
        list.forEach(investRankView -> {
            investRankView.setPhone(CommonUtil.maskedPhone(investRankView.getPhone()));
            stringRedisTemplate.
                    opsForZSet().
                    add(RedisConstant.INVEST_RANK,
                            investRankView.getPhone(), investRankView.getMoney());
        });
        //默认十天更新一次排行榜
        stringRedisTemplate.expire(RedisConstant.INVEST_RANK,
                RedisConstant.INVEST_RANK_TTL, TimeUnit.DAYS);
        return Result.ok(list);
    }

}
